package org.robot.scm.platform.registry;

import cn.hutool.core.collection.ConcurrentHashSet;
import it.tdlight.Init;
import it.tdlight.Log;
import it.tdlight.Slf4JLogMessageHandler;
import it.tdlight.client.APIToken;
import it.tdlight.client.AuthenticationSupplier;
import it.tdlight.client.SimpleAuthenticationSupplier;
import it.tdlight.client.SimpleTelegramClientBuilder;
import it.tdlight.client.SimpleTelegramClientFactory;
import it.tdlight.client.TDLibSettings;
import it.tdlight.jni.TdApi.MessageContent;
import it.tdlight.jni.TdApi.UpdateNewMessage;
import it.tdlight.util.UnsupportedNativeLibraryException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.platform.AbstractRegistry;
import org.robot.scm.platform.registry.strategy.AbstractMessageHandler;
import org.robot.scm.platform.server.telegram.ScmTelegram;
import org.robot.scm.pojos.config.base.BasePlatform;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.utils.JsonHelper;

/**
 * @Author : Awn create on 2024/5/12 19:36
 */
@Slf4j
public class TelegramRegistry extends AbstractRegistry {

    private static ScmTelegram telegram;

    public static final List<String> filterWords;

    // 最后聊天ID
    public static AtomicReference<Long> lastChatId = new AtomicReference<>(0L);


    // 类似的脚本文件名称
    public static AtomicReference<String> likeSqlFile = new AtomicReference<>("");

    // 类似的环境套
    public static ConcurrentHashSet<Integer> likeEnvIds = new ConcurrentHashSet<>();

    // 类似的脚本文件
    public static AtomicReference<String> likeSqlKey = new AtomicReference<>("");

    /**
     * 名称映射
     */
    public static final Map<String, String> nameMap = new HashMap<>() {
        {
            put("dba yj", "天魁星");
            put("阿易", "天罡星");
            put("willie", "天机星");
            put("caterpillar", "天闲星");
            put("Nona me", "天勇星");
            put("GG Bond", "天勇星");
            put("51员工【总群】", "梁山汇");
            put("51-数据库操作", "江州帮");
        }
    };

    static {
        try {
            File file = new File("config/filter.json");
            String words = FileUtils.readFileToString(file, StandardCharsets.UTF_8.name());
            filterWords = JsonHelper.toList(words);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendToLastChat(String msg) {
        log.info("deprecated method: {}", msg);
    }

    @Override
    public int getOrder() {
        // 阻塞线程，顺序排最后
        return Integer.MAX_VALUE;
    }

    public static void clearSqlLike() {
        likeEnvIds.clear();
        likeSqlFile.set(StringUtils.EMPTY);
        likeSqlKey.set(StringUtils.EMPTY);
    }

    @SneakyThrows
    @Override
    public void registry() {
        if (!AbstractMonitor.mainConfig.getEnables().contains(PlatformEnum.TELEGRAM.getVal())) {
            return;
        }
        init();
        if (Objects.isNull(telegram)) {
            return;
        }
        log.info("close telegram ... ok");
        telegram.getClient().sendClose();
    }


    private static void init() throws UnsupportedNativeLibraryException {
        BasePlatform platform = AbstractMonitor.mainConfig.getPlatform(PlatformEnum.TELEGRAM);
        long adminId = Long.getLong("it.tdlight.example.adminid", platform.getTelegramId());

        Init.init();

        // Set the log level
        Log.setLogMessageHandler(1, new Slf4JLogMessageHandler());

        // Create the client factory
        try (SimpleTelegramClientFactory clientFactory = new SimpleTelegramClientFactory()) {
            // Obtain the API token
            APIToken apiToken = new APIToken(platform.getAppId(), platform.getApiHash());

            // Configure the client
            TDLibSettings settings = TDLibSettings.create(apiToken);

            // Configure the session directory.
            Path sessionPath = Paths.get("session");
            settings.setDatabaseDirectoryPath(sessionPath.resolve("data"));
            settings.setDownloadedFilesDirectoryPath(sessionPath.resolve("downloads"));

            // Prepare a new client builder
            SimpleTelegramClientBuilder clientBuilder = clientFactory.builder(settings);

            // Configure the authentication info
            SimpleAuthenticationSupplier<?> authenticationData = AuthenticationSupplier.user(platform.getPhoneNumber());

            // Create and start the client
            new ScmTelegram(clientBuilder, authenticationData, adminId, platform.getSockProxy(), TelegramRegistry::newMessage, TelegramRegistry::setClient);
        }
    }

    private static void setClient(ScmTelegram scmTelegram) {
        telegram = scmTelegram;
    }

    /**
     * TG收到新消息回调处理
     */
    private static void newMessage(UpdateNewMessage update, ScmTelegram scmTelegram) {
        // Get the message TdApi.UpdateNewMessage updatecontent
        MessageContent messageContent = update.message.content;

        // 记录每次最后的聊天ID
        lastChatId.set(update.message.chatId);

        // Get the message text
        AbstractMessageHandler.handleMessage(scmTelegram, update.message, messageContent);
    }

}
